﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HotelManagement.BLO;
using HotelManagement.DTO;
using HotelManagement.Rent;

namespace HotelManagement.Room
{
    public partial class RoomManagement : UserControl
    {
        private string defSelectedDirection = "--Chọn hướng--";
        private BindingSource bindingSource;
        private BindingSource bindingSourceRT;
        private RoomDTO room;
        private RoomTypeDTO roomType;
        private RoomBLO bloR;
        private RoomTypeBLO bloRT;
        private DataTable tblRoom;
        private DataTable tblRoomType;
        private CheckInput chk;
        private List<string> lstStatus;
        //Equipments
        private Room_EquipmentBLO bloEquipmentRoom;
        private EquipmentBLO bloEquipment;
        private DataTable tblEquipment;
        private DataTable tblEquipmentRoom;

        public RoomManagement()
        {
            InitializeComponent();
        }
        private void RoomManagement_Load(object sender, EventArgs e)
        {
            Init();
        }
        private void Init()
        {
            bindingSource = new BindingSource();
            bindingSourceRT = new BindingSource();
            room = new RoomDTO();
            roomType = new RoomTypeDTO();
            bloR = new RoomBLO();
            bloRT = new RoomTypeBLO();
            bloEquipment = new EquipmentBLO();
            bloEquipmentRoom = new Room_EquipmentBLO();
            chk = new CheckInput();
            lstStatus = HotelManagement.CheckInput.lstStatus;
            RefreshTable();
            InitialGridView();
            InitComboBoxData();
            //ListEquipment();
        }
        private void InitComboBoxData()
        {
            tblRoomType = bloRT.Select();
            //init for the cmbRoomType
            cmbRoomType.DisplayMember = "RoomTypeName";
            cmbRoomType.ValueMember = "RoomTypeID";
            cmbRoomType.DataSource = tblRoomType;
            cmbRoomType.SelectedIndex = 0;

            //cmbDirection
            List<string> lstDirection = new List<string>();
            lstDirection.Add(defSelectedDirection);
            lstDirection.Add("Đông");
            lstDirection.Add("Bắc");
            lstDirection.Add("Tây");
            lstDirection.Add("Nam");
            lstDirection.Add("Đông-Bắc");
            lstDirection.Add("Tây-Nam");
            lstDirection.Add("Tây-Bắc");
            lstDirection.Add("Đông-Nam");
            cmbRoomDirection.DataSource = lstDirection;
            cmbRoomDirection.SelectedIndex = 0;

            //cmbStatus
            //List<string> lstStatus = new List<string>();
            //lstStatus.Add("Trống");
            //lstStatus.Add("Còn chỗ trống");
            //lstStatus.Add("Hết chỗ trống");
            //lstStatus.Add("Đã được đặt chỗ");
            cmbStatus.DataSource = lstStatus;
            cmbStatus.SelectedIndex = 0;

            //cmbSearchRoomName
            tblRoom = (DataTable)bindingSource.DataSource;
            List<string> lstName = new List<string>();
            lstName.Add("Chọn phòng");
            foreach (DataRow row in tblRoom.Rows)
            {
                lstName.Add(row["RoomName"].ToString());
            }
            cmbSearchRoomName.DataSource = lstName;
            cmbSearchRoomName.SelectedIndex = 0;

            //cmbSearchRoomType
            List<string> lstType = new List<string>();
            lstType.Add("Chọn loại phòng");
            foreach (DataRow row in ((DataTable)bindingSource.DataSource).Rows)
            {
                lstType.Add(row["RoomTypeName"].ToString());
            }
            cmbSearchRoomType.DataSource = lstType;

            //cmbSearchRoomStatus
            List<string> lstStatuss = new List<string>();
            lstStatuss.Add("Trạng thái");
            foreach (string row in lstStatus)
            {
                lstStatuss.Add(row);
            }
            cmbSearchRoomStatus.DataSource = lstStatuss;

        }
        /*
         * Hàm này dùng để tạo ra danh sách các tiện nghi trong phòng
         */
        private void ListEquipment()
        {

            chkEquipments.Items.Clear();
            lstEquipments.Items.Clear();
            //if (txtRoomID.Text != "")
            {
                //MessageBox.Show(txtRoomID.Text);
                try
                {
                    tblEquipmentRoom = bloEquipmentRoom.SelectEquipmentOfARoom(int.Parse(txtRoomID.Text));
                }
                catch (System.Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                CheckListItem();
            }
        }
        /*Hàm này dùng để kiểm tra trong danh sách các tiện nghi của một phòng
         * tiện nghi nào phòng có thì đưa sang cột bên phải, và tiện nghi nào chưa có thì đưa sang cột trái
         */
        private void CheckListItem()
        {
            try
            {
                foreach (DataRow row in tblEquipmentRoom.Rows)
                {
                    if (int.Parse(row["Available"].ToString()) == 1)
                    {
                        if (lstEquipments.Items.IndexOf(row["EquipmentName"].ToString()) < 0)
                        {
                            lstEquipments.Items.Add(row["EquipmentName"].ToString());
                        }
                        for (int i = 0; i < chkEquipments.Items.Count; i++)
                        {
                            if (row["EquipmentName"].ToString() == chkEquipments.Items[i].ToString())
                            {
                                chkEquipments.Items.RemoveAt(i);
                            }
                        }
                    }
                    else
                    {
                        //MessageBox.Show(chkEquipments.Items.IndexOf(row["EquipmentName"].ToString()).ToString());
                        if (chkEquipments.Items.IndexOf(row["EquipmentName"].ToString()) < 0)
                        {
                            chkEquipments.Items.Add(row["EquipmentName"].ToString());
                        }
                        for (int i = 0; i < lstEquipments.Items.Count; i++)
                        {
                            if (row["EquipmentName"].ToString() == lstEquipments.Items[i].ToString())
                            {
                                lstEquipments.Items.RemoveAt(i);
                            }
                        }
                    }
                }
            }
            catch (NullReferenceException er)
            {
                //MessageBox.Show(er.Message);
            }

        }

        private void InitialGridView()
        {
            dataGridViewRoom.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            DataGridViewCellStyle columnHeaderStyle =
            new DataGridViewCellStyle();

            columnHeaderStyle.BackColor = Color.Blue;
            columnHeaderStyle.Font = new Font("Verdana", 9, FontStyle.Bold);

            dataGridViewRoom.ColumnHeadersDefaultCellStyle = columnHeaderStyle;

            try
            {
                dataGridViewRoom.Columns["RoomID"].HeaderText = "Mã Phòng";
                dataGridViewRoom.Columns["RoomName"].HeaderText = "Tên Phòng";
                dataGridViewRoom.Columns["RoomTypeName"].HeaderText = "Loại Phòng";
                dataGridViewRoom.Columns["NumOfBed"].HeaderText = "Số Giường";
                dataGridViewRoom.Columns["NumOfPerson"].HeaderText = "Số khách";
                dataGridViewRoom.Columns["Direction"].HeaderText = "Phương hướng";
                dataGridViewRoom.Columns["Views"].HeaderText = "Mô tả";
                dataGridViewRoom.Columns["Status"].HeaderText = "Tình trạng";
                dataGridViewRoom.Columns["LastOwner"].HeaderText = "Owner";
            }
            catch (System.Exception es)
            {
                //MessageBox.Show(es.ToString());
            }
            // dataGridViewRoomType.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridViewRoomType.ColumnHeadersDefaultCellStyle = columnHeaderStyle;
            try
            {
                dataGridViewRoomType.Columns["RoomTypeID"].HeaderText = "Mã loại";
                dataGridViewRoomType.Columns["RoomTypeName"].HeaderText = "Tên loại";
                dataGridViewRoomType.Columns["Price"].HeaderText = "Giá cả/ngày";
                dataGridViewRoomType.Columns["Describe"].HeaderText = "Ghi chú";
            }
            catch (System.Exception et)
            {

            }
        }
        private void RefreshTable()
        {
            bindingSource.DataSource = bloR.SelectAllWithTypeName();
            bindingSource.Filter = "";
            this.dataGridViewRoom.DataSource = bindingSource;

            bindingSourceRT.DataSource = bloRT.Select();
            bindingSourceRT.Filter = "";
            dataGridViewRoomType.DataSource = bindingSourceRT;
        }
        /*
         * Hàm này dùng để lưu lại danh sách những tiện nghi của phòng đang chọn
         * Hàm này khi truyền dữ liệu xuống BLO thì sẽ lấy RoomID từ txtRoomID chứ không lấy từ table tblEquipmentRoom
         * vì để bao luôn trường hợp người dùng thêm một phòng mới, thêm phòng mới thì RoomID như vậy là không đúng
         */
        private void SaveEquipment()
        {
            int eID, eAv;
            string err = "";
            try
            {
                foreach (DataRow row in tblEquipmentRoom.Rows)
                {
                    eID = int.Parse(row["EquipmentID"].ToString());
                    eAv = int.Parse(row["Available"].ToString());
                    Room_EquipmentDTO temp = new Room_EquipmentDTO(int.Parse(txtRoomID.Text), eID, eAv);
                    if (!bloEquipmentRoom.InsertOrUpdate(temp))
                    {
                        err += "[ " + row["EquipmentID"].ToString() + " ]";
                    }
                }
            }
            catch (NullReferenceException ea)
            {
                MessageBox.Show(ea.Message, "Exception o SaveEquipemt");
            }

            if (err != "")
            {
                MessageBox.Show(err, "Thông báo");
            }
        }

        private void btnUpdateRoom_Click(object sender, EventArgs e)
        {
            if (!chk._isRoomName(txtRoomName.Text))
            {
                MessageBox.Show(CheckInput.ERR_ROOMNAME, CheckInput.ERR_TITILE);
                txtRoomName.Focus();
                txtRoomName.Select();
                return;
            }
            if (txtRoomID.Text == "")
            {
                MessageBox.Show(CheckInput.ERR_NO_ROOM_NAME_SELECTED, CheckInput.ERR_TITILE);
                return;
            }
            room.RoomID = int.Parse(txtRoomID.Text);
            room.RoomName = txtRoomName.Text;
            room.RoomTypeID = (int)cmbRoomType.SelectedValue;
            room.NumOfBed = int.Parse(cmbNumOfBed.Text);
            room.NumOfPerson = int.Parse(cmbNumOfPerson.Text);
            if (cmbRoomDirection.Text == defSelectedDirection)
            {
                room.Direction = "";
            }
            else
                room.Direction = cmbRoomDirection.Text;
            room.Views = txtViews.Text;

            SaveEquipment();
            if (!bloR.UpdateInfo(room))
            {
                MessageBox.Show(CheckInput.ERR_UPDATE, CheckInput.ERR_TITILE);
                return;
            }
            else
            {
                RefreshTable();
                MessageBox.Show(CheckInput.SUC_UPDATE, CheckInput.ERR_TITILE);
                chk.SelectExecuteRow(this.dataGridViewRoom, int.Parse(txtRoomID.Text));
            }
        }

        private void btnInsertRoom_Click(object sender, EventArgs e)
        {
            //MessageBox.Show((cmbRoomType.SelectedValue).ToString());

            if (!chk._isRoomName(txtRoomName.Text))
            {
                MessageBox.Show(CheckInput.ERR_ROOMNAME, CheckInput.ERR_TITILE);
                txtRoomName.Focus();
                txtRoomName.Select();
                return;
            }
            //room.RoomID = int.Parse(txtRoomID.Text);
            room.RoomName = txtRoomName.Text;
            room.RoomTypeID = (int)cmbRoomType.SelectedValue;
            room.NumOfBed = int.Parse(cmbNumOfBed.Text);
            room.NumOfPerson = int.Parse(cmbNumOfPerson.Text);
            if (cmbRoomDirection.Text == defSelectedDirection)
            {
                room.Direction = "";
            }
            else
                room.Direction = cmbRoomDirection.Text;
            room.Views = txtViews.Text;
            room.Status = 0;

            if (!bloR.Insert(room))
            {
                MessageBox.Show(CheckInput.ERR_INSERT, CheckInput.ERR_TITILE);
                return;
            }

            RefreshTable();
            int idx = bloR.SelectLastInsertID();
            //Tạo ra những tiện nghi mặc định true theo phòng vừa thêm vào
            tblEquipment = bloEquipment.Select();
            foreach (DataRow row in tblEquipment.Rows)
            {
                int qAv = 1;
                if (tblEquipmentRoom != null)
                {
                    foreach (DataRow ro in tblEquipmentRoom.Rows)
                    {
                        if (int.Parse(row["EquipmentID"].ToString()) == int.Parse(ro["EquipmentID"].ToString()))
                        {
                            qAv = int.Parse(ro["Available"].ToString());
                            break;
                        }
                    }
                }
                Room_EquipmentDTO qui = new Room_EquipmentDTO(idx, int.Parse(row["EquipmentID"].ToString()), qAv);
                bloEquipmentRoom.Insert(qui);
            }
            //txtRoomID.Text = idx.ToString();
            MessageBox.Show(CheckInput.SUC_INSERT, CheckInput.ERR_TITILE);
            chk.SelectExecuteRow(this.dataGridViewRoom, idx);
            //Cập nhật lại danh sách của các tiện nghi
            //SaveEquipment();
        }

        private void dataGridViewRoom_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int r = e.RowIndex;
            try
            {
                CustomerBLO bloC=new CustomerBLO();
                DataGridViewRow row = dataGridViewRoom.Rows[r];
                row = dataGridViewRoom.Rows[e.RowIndex];
                txtRoomID.Text = row.Cells["RoomID"].Value.ToString();
                txtRoomName.Text = row.Cells["RoomName"].Value.ToString();
                cmbRoomType.Text = row.Cells["RoomTypeName"].Value.ToString();
                cmbNumOfBed.Text = row.Cells["NumOfBed"].Value.ToString();
                cmbNumOfPerson.Text = row.Cells["NumOfPerson"].Value.ToString();
                cmbRoomDirection.Text = row.Cells["Direction"].Value.ToString();
                txtViews.Text = row.Cells["Views"].Value.ToString();
                cmbStatus.SelectedIndex = (int)row.Cells["Status"].Value;
                txtOwnerID.Text = row.Cells["LastOwner"].Value.ToString();
                txtOwnerName.Text = bloC.GetCustomerFromID(int.Parse(txtOwnerID.Text)).Name;
                //txtViews.Text=row.Cells["Views"]
            }
            catch (System.Exception erk)
            {
                //MessageBox.Show(erk.Message);
            }
        }
        #region "Room Search"
        private string GetFilterExpression()
        {
            string filter = "";
            if (cmbSearchRoomName.SelectedIndex != 0)
            {
                filter += "RoomName like '%" + cmbSearchRoomName.Text + "%'";
                if (cmbSearchRoomType.SelectedIndex != 0)
                {
                    filter += " AND RoomTypeName like '%" + cmbSearchRoomType.Text + "%'";
                }
                if (cmbSearchRoomStatus.SelectedIndex != 0)
                {
                    filter += " AND Status = " + (cmbSearchRoomStatus.SelectedIndex - 1);
                }

            }
            else
                if (cmbSearchRoomType.SelectedIndex != 0)
                {
                    filter += "RoomTypeName like '%" + cmbSearchRoomType.Text + "%'";
                    if (cmbSearchRoomStatus.SelectedIndex != 0)
                    {
                        filter += " AND Status =" + (cmbSearchRoomStatus.SelectedIndex - 1);
                    }

                }
                else
                    if (cmbSearchRoomStatus.SelectedIndex != 0)
                    {
                        filter += "Status =" + (cmbSearchRoomStatus.SelectedIndex - 1);

                    }
            return filter;
        }

        private void btnRoomSearch_Click(object sender, EventArgs e)
        {
            bindingSource.Filter = "";
            bindingSource.Filter = GetFilterExpression();
            dataGridViewRoom.Refresh();
        }
        #endregion

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            this.txtRoomID.Text = "";
            txtRoomName.Text = "";
            cmbRoomType.SelectedIndex = 0;
            cmbRoomDirection.SelectedIndex = 0;
            cmbStatus.SelectedIndex = 0;
            cmbSearchRoomName.SelectedIndex = 0;
            cmbSearchRoomType.SelectedIndex = 0;
            cmbSearchRoomStatus.SelectedIndex = 0;
            RefreshTable();
        }

        private void cmbRoomType_TextChanged(object sender, EventArgs e)
        {
            ComboBox cmb = (ComboBox)sender;
            string tam = (cmb.SelectedIndex).ToString();
            int idx = int.Parse(tam);
            lblRoomTypeName.Text = (tblRoomType.Rows[idx]["RoomTypeName"]).ToString();
            lblRoomTypePrice.Text = (tblRoomType.Rows[idx]["Price"]).ToString();
            lblRoomTypeDescribe.Text = (tblRoomType.Rows[idx]["Describe"]).ToString();
            //MessageBox.Show(tam);
            chk.SelectExecuteRow(dataGridViewRoomType, int.Parse((cmbRoomType.SelectedValue).ToString()));
        }

        private void btnAddRoomType_Click(object sender, EventArgs e)
        {
            int idx = int.Parse((cmbRoomType.SelectedValue).ToString());
            CreateNewRoomType frmRT = new CreateNewRoomType(idx);
            if (frmRT.ShowDialog(this) == DialogResult.OK)
            {
                RefreshTable();
                InitComboBoxData();
                chk.SelectExecuteRow(dataGridViewRoomType, idx);
            }
        }

        private void txtRoomID_TextChanged(object sender, EventArgs e)
        {
            if (txtRoomID.Text != "")
            {
                chkEquipments.Items.Clear();
                lstEquipments.Items.Clear();
                //if (txtRoomID.Text != "")
                {
                    //MessageBox.Show(txtRoomID.Text);
                    try
                    {
                        tblEquipmentRoom = bloEquipmentRoom.SelectEquipmentOfARoom(int.Parse(txtRoomID.Text));
                    }
                    catch (System.Exception el)
                    {
                        MessageBox.Show(el.Message);
                    }
                    CheckListItem();
                }
            }
        }

        private void btnLR_Click(object sender, EventArgs e)
        {
            if (txtRoomID.Text == "")
            {
                MessageBox.Show("Chưa có phòng nào được chọn", "Thông báo");
                return;
            }
            try
            {
                foreach (string item in chkEquipments.CheckedItems)
                {
                    foreach (DataRow row in tblEquipmentRoom.Rows)
                    {
                        if (item.ToString() == row["EquipmentName"].ToString())
                        {
                            row["Available"] = 1;

                        }
                    }
                }
                CheckListItem();

            }
            catch (System.Exception el)
            {

            }
        }

        private void btnRL_Click(object sender, EventArgs e)
        {
            try
            {
                string sel = lstEquipments.SelectedItem.ToString();
                foreach (DataRow row in tblEquipmentRoom.Rows)
                {
                    if (row["EquipmentName"].ToString() == sel)
                    {
                        row["Available"] = 0;
                        break;
                    }
                }
                CheckListItem();
            }
            catch (System.Exception er)
            {

            }

        }

        private void btnSelectARoom_Click(object sender, EventArgs e)
        {
            if (cmbStatus.SelectedIndex == HotelManagement.CheckInput.STATUS_CHECK_IN)
            {
                MessageBox.Show("Phòng [" + txtRoomName.Text + "] không còn chỗ trống", "Thông báo");
                return;
            }
            if (txtRoomID.Text=="")
            {
                MessageBox.Show("Phải chọn một phòng trước khi thao tác");
                return;
            }
            RentRoomManagement.room.RoomID = int.Parse(txtRoomID.Text);
            RentRoomManagement.room.RoomName = txtRoomName.Text;
            RentRoomManagement.room.RoomTypeID = (int)cmbRoomType.SelectedValue;
            RentRoomManagement.room.NumOfBed = int.Parse(cmbNumOfBed.Text);
            RentRoomManagement.room.NumOfPerson = int.Parse(cmbNumOfPerson.Text);
            if (cmbRoomDirection.Text == defSelectedDirection)
            {
                RentRoomManagement.room.Direction = "";
            }
            else
                RentRoomManagement.room.Direction = cmbRoomDirection.Text;
            RentRoomManagement.room.Views = txtViews.Text;
            RentRoomManagement.room.Status = bloR.GetStatusIDFromStatusName(cmbStatus.Text);
            RentRoomManagement.room.LastOwner = int.Parse(txtOwnerID.Text);
            foreach (string str in lstEquipments.Items)
            {
                RentRoomManagement.lstRoomEquipment.Add(str);
            }
        }

    }
}
